package com.yangmao.mvc.controller;

import com.github.pagehelper.PageInfo;
import com.yangmao.entity.Physical;
import com.yangmao.service.api.PhysicalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author ‘洋毛’
 * @version 1.0
 * @description: TODO
 * @date 2022/1/11 14:25
 */
@Controller
public class PhysicalController {
    @Autowired
    private PhysicalService PhysicalService;

    @GetMapping("/physical/all.json")
    public ModelAndView getAllPhysical(@RequestParam(name="page",required = true,defaultValue = "1") Integer page,
                                           @RequestParam(name="size",required = true,defaultValue = "4")Integer size) {
        ModelAndView mv = new ModelAndView();

        List<Physical> Physical = PhysicalService.getAllPhysical(page,size);

        PageInfo pageInfo = new PageInfo(Physical);

        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("physical_list");

        return mv;
    }

    @RequestMapping("/physical/edit.html")
    public ModelAndView editPhysical(@RequestParam("id") String id, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        Physical Physical = PhysicalService.getPhysicalById(id);
        mv.addObject("physical", Physical);
        mv.setViewName("physical_edit");

        return mv;
    }

    @PostMapping("/physical/update.html")
    public String updatePhysical(Physical Physical) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date();
        String str = simpleDateFormat.format(d); //将日期转换为字符串且格式按照之前制定的

        Physical.setUpdate_time(str);
        PhysicalService.updatePhysical(Physical);
        return "redirect:/physical/all.json";
    }

    @RequestMapping("/physical/delete.html")
    public String deletePhysical(@RequestParam("id") String id) {
        PhysicalService.deletePhysical(id);
        return "redirect:/physical/all.json";
    }

    @PostMapping("/physical/add.html")
    public String addPhysical(Physical Physical){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date();
        String str = simpleDateFormat.format(d); //将日期转换为字符串且格式按照之前制定的

        Physical.setCreate_time(str);
        Physical.setUpdate_time(str);

        PhysicalService.addPhysical(Physical);

        return "redirect:/physical/all.json";
    }
}
